package com.gin.kotlin.no_gay_alliance.fragment.main.usercenter

import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.webkit.JavascriptInterface
import androidx.core.view.MenuProvider
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.SignatureEditActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.PhotoPreviewUtils
import com.gin.kotlin.no_gay_alliance.databinding.FragmentUserCenterTabSignatureBinding
import com.gin.kotlin.no_gay_alliance.listener.PhotoPreviewLongClickListener
import com.gin.kotlin.no_gay_alliance.model.UserDetailModel
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.kotlin.no_gay_alliance.webview.BbsCodeWebViewClient
import com.gin.nga.bbscode.BbsCodeNode
import com.gin.nga.enums.ImageThumb
import com.gin.nga.utils.BbsCodeRenderer

class UserCenterTabSignatureFragment:AbstractUserCenterTabFragment<FragmentUserCenterTabSignatureBinding>,MenuProvider  {
    constructor() : super()
    constructor(data: UserDetailModel?) : super(data)

    override fun onCreateView() {
        val b = this.b ?: return
        val template = requireContext().assets.open("template.html").bufferedReader().readText()

        b.webView.webViewClient = BbsCodeWebViewClient(requireContext())
        b.webView.addJavascriptInterface(this, "android")
        userDetail.signature?.also {
            val renderer = BbsCodeRenderer(GlobalProperty.getInstance().domain, App.INSTANCE.emoteGroup)
            val codeNodes = BbsCodeNode.parseContent(it)
            val html = renderer.render(codeNodes)
            b.webView.loadDataWithBaseURL(template.replace("[回复容器占位]",html))
        }
    }

    /**
     * 预览指定url的图片
     * @param url String
     */
    @JavascriptInterface
    fun previewByUrl(url: String) {
        // 打开预览的界面(缩略图所处界面)，预览生命周期与activity绑定
        var u = url

        // 移除缩略图后缀
        ImageThumb.entries.forEach {
            if (u.endsWith(it.suffix)) u = u.replace(it.suffix, "")
        }

        App.INSTANCE.handler?.post {
            PhotoPreviewUtils.build(requireActivity(), listOf(u), listener = PhotoPreviewLongClickListener(requireActivity()) { _ ->
                run {
                    // 检查链接形式，如果是附件格式转换为code
                    val code = if (u.startsWith(ImageThumb.PREFIX)) u.replace(ImageThumb.PREFIX, "").let { "[img]./$it[/img]" } else ""
                    PhotoPreviewLongClickListener.PreviewImage(u, code)
                }
            }).build().show()
        }
    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.signature,menu)
    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        if (menuItem.itemId==R.id.mi_edit){
            SignatureEditActivity.start(requireContext(),userDetail.signature,userDetail.userId)
            return true
        }
        return false
    }
}